﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Net.Http;

namespace TomNet.AspNetCore.Mvc
{
    public static class ServiceCollectionExtensions
    {
        public static IServiceCollection AddApiControllers(this IServiceCollection services,
            Action<MvcOptions> mvcOptions = null,
            Action<MvcNewtonsoftJsonOptions> jsonOptions = null)
        {
            services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

            IMvcBuilder builder;

            if (mvcOptions == null)
            {
                builder = services.AddControllers();
            }
            else
            {
                builder = services.AddControllers(mvcOptions);
            }

            services.Configure<ApiBehaviorOptions>(options =>
            {
                options.SuppressModelStateInvalidFilter = true;
            });

            if (jsonOptions != null)
            {
                builder.AddNewtonsoftJson(jsonOptions);
            }
            else
            {
                builder.AddNewtonsoftJson(options =>
                {
                    // 默认序列化规则
                    //options.SerializerSettings.ContractResolver = new DefaultContractResolver();

                    // 修改属性名称的序列化方式，首字母小写，即驼峰样式
                    options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

                    // 日期类型默认格式化处理
                    options.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
                    options.SerializerSettings.DateFormatString = "yyyy/MM/dd HH:mm:ss";

                    // 忽略循环引用
                    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

                    // 空值处理,开启这个选项后，空值将被序列化
                    // options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
                });
            }
            return services;
        }


        public static IServiceCollection AddHttpClients(this IServiceCollection services)
        {
            //for IHttpClientFactory
            services.AddHttpClient("InternalAccess")
                .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler()
                {
                    UseProxy = false,
                    AllowAutoRedirect = false,
                    UseDefaultCredentials = true,
                    //Do not verify SSL certificate
                    ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; }
                });
            return services;
        }
    }
}
